const units = ['B', 'KB', 'MB', 'GB', 'TB'];

export function formatBytes(bytes: number, isBinary = true): string {
  const factor = isBinary ? 1024 : 1000;
  let unitIndex = 0;

  while (bytes >= factor && unitIndex < units.length - 1) {
    bytes /= factor;
    unitIndex++;
  }

  return `${bytes.toFixed(2)} ${units[unitIndex]}`;
}

export function formatBytesStr(byteStr: string, isBinary = true): number {
  const factor = isBinary ? 1024 : 1000;

  const arr = byteStr.split(' ');
  const num = +arr[0];
  const unit = arr[1].toUpperCase();
  const unitIndex = units.indexOf(unit);

  return Math.round(num * Math.pow(factor, unitIndex));
}
